﻿using System;

namespace Common.Data
{
    public class DateTimeHelper
    {
        /// <summary>
        /// 获取本月第一天
        /// </summary>
        /// <returns></returns>
        public static DateTime GetMFirstDay()
        {
            DateTime dt = DateTime.Now;
            //本月第一天时间   
            DateTime dt_First = dt.AddDays(-(dt.Day) + 1);
            return dt_First;
        }

        /// <summary>
        /// 获取本月最后一天
        /// </summary>
        /// <returns></returns>
        public static DateTime GetMLastDay()
        {
            DateTime dt = DateTime.Now;
            //将月数+1
            //本月最后一天时间
            DateTime dt_Last = dt.AddMonths(1).AddDays(-(dt.Day));
            return dt_Last;
        }

        /// <summary>
        /// 获取按年月日算的时间差
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="differenceYear">年份差</param>
        /// <param name="differenceMonth">月份差</param>
        /// <param name="differenceDay">天数差</param>
        /// <param name="ts">时间部分</param>
        /// <returns>结束时间是否大于开始时间</returns>
        public static bool GetDateTimeDifference(DateTime startTime, DateTime endTime, out int differenceYear, out int differenceMonth, out int differenceDay, out TimeSpan ts)
        {
            bool bol = endTime > startTime;
            if (startTime > endTime)
            {
                DateTime proxyTime = startTime;
                startTime = endTime;
                endTime = proxyTime;
            }
            differenceYear = 0;
            differenceMonth = 0;
            differenceDay = 0;
            //时间差
            if (startTime.TimeOfDay > endTime.TimeOfDay)
            {
                endTime = endTime.AddDays(-1);
                ts = DateTime.MinValue.AddDays(((endTime.TimeOfDay - startTime.TimeOfDay).TotalDays + 1)).TimeOfDay;
            }
            else
            {
                ts = endTime.TimeOfDay - startTime.TimeOfDay;
            }
            //日期差
            if (startTime.Day > endTime.Day)
            {
                endTime = endTime.AddMonths(-1);
                differenceDay = DateTime.DaysInMonth(endTime.Year, endTime.Month) + endTime.Day - startTime.Day;
            }
            else
            {
                differenceDay = endTime.Day - startTime.Day;
            }
            //月份,年份
            differenceMonth = (endTime.Year - startTime.Year) * 12 + endTime.Month - startTime.Month;
            if (differenceMonth >= 12)
            {
                differenceYear = differenceMonth / 12;
                differenceMonth = differenceMonth % 12;
            }
            return bol;
        }
    }
}
